const authCodeFunc = require('../../../utils/authCode');
const Tag = require('../../../models/blog_tags');
const Category = require('../../../models/blog_category');
const User = require('../../../models/admin_users');
const knex = require('../../../models/knex');

/**
 * 标签管理控制器
 */
const ControllerTags = {
    /* 获取列表 */
    getList: async function (req, res, next) {
        try {
            let { per_page, page, keywor, } = req.query;
            let offset = (per_page * (page - 1)) || 0; //计算当前页
            let tags = Tag.table;
            let categorys = Category.table;
            let users = User.table;
            let ac = '';

            if (keywor) {
                keywor = decodeURI(keywor); // 对前端传递过来的信息进行解码
                ac = `${tags}.title = ${keywor}`;
            }

            const list = await knex(tags)
                .join(categorys, `${tags}.category_id`, `${categorys}.id`)
                .join(users, `${tags}.issuer_id`, `${users}.id`)
                .whereRaw(ac) // 条件搜索
                .limit(Number(per_page)).offset(Number(offset)) // 分页查询
                .orderBy(`${tags}.sort`) // 排序
                .select(
                    `${tags}.id`, `${tags}.title`, `${tags}.desc`,
                    `${tags}.sort`, `${tags}.category_id`, `${tags}.issuer_id`,
                    `${tags}.created_time`, `${categorys}.title as category_title`,
                    `${users}.user_name as issuer_name`,
                )

            let total = (await knex(tags).where('title', 'like', `%${keywor}%`)).length;
            let number = Math.ceil(total / per_page); // 计算出信息总页数

            res.json({ code: 200, data: { list, total, number } })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
    /* 获取详情 */
    getById: async function (req, res, next) {
        try {
            let { id } = req.query;

            const tags = await Tag.select({ id });

            res.json({ code: 200, data: tags[0] })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
    /* 创建 */
    Insert: async function (req, res, next) {
        try {
            let authorization = req.headers.authorization;
            let tokens = authorization.split(' ');
            let user_decode = authCodeFunc(tokens[1], 'DECODE');
            let user_info = user_decode.str.split('\t');
            let issuer_id = user_info[0];
            let { category_id, title, desc } = req.body;
            let params = { category_id, title, issuer_id, created_time: new Date().getTime() };

            if (!category_id || !title) return res.json({ code: 0, msg: '缺少必要参数' });

            // if (!title) return res.json({ code: 0, msg: '未填写标签名' });

            if (desc) params.desc = desc;

            await Tag.insert(params)

            res.json({ code: 200, msg: '创建成功' })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    /* 编辑 */
    update: async function (req, res, next) {
        try {
            let authorization = req.headers.authorization;
            let tokens = authorization.split(' ');
            let user_decode = authCodeFunc(tokens[1], 'DECODE');
            let user_info = user_decode.str.split('\t');
            let modifier_id = user_info[0];
            let { id, category_id, title, desc } = req.body;
            let params = { category_id, title, modifier_id, update_time: new Date().getTime() };

            if (!category_id || !title) return res.json({ code: 0, msg: '缺少必要参数' });

            // if (!title) return res.json({ code: 0, msg: '未填写分类名' });

            if (desc) params.desc = desc;

            await Tag.update(id, params)

            res.json({ code: 200, msg: '编辑成功' })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
    /* 删除 */
    del: async function (req, res, next) {
        try {
            let { id } = req.body;
            let ids = null;

            if (typeof (id) === 'number') await Tag.delete(id)

            if (typeof (id) === 'string') {
                ids = id.split(',');

                await Tag.batchDel(ids)
            }
            res.json({ code: 200, msg: '删除成功' })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    /* 排序 */
    onUpdateSort: async function (req, res, next) {
        try {
            let sortList = JSON.parse(req.body.sortList);

            sortList.forEach(async data => {
                let id = data.id;

                await Tag.update(id, { sort: data.sort })
            })

            res.json({ code: 200, msg: "排序成功" })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    }
}

module.exports = ControllerTags;
